package com.huluobo.a2302mdmdemo.videos.pages

import android.content.Context
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.MediaItem
import androidx.media3.common.Player.REPEAT_MODE_ONE
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2302mdmdemo.R
import com.huluobo.a2302mdmdemo.demo.LikeView
import com.huluobo.a2302mdmdemo.videos.VideoIntent
import com.huluobo.a2302mdmdemo.videos.VideoViewModel
import com.huluobo.a2302mdmdemo.videos.entity.CommentEntity
import com.huluobo.a2302mdmdemo.videos.entity.CommentEntityItem
import com.huluobo.lib_base.entity.VideoEntity
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import com.huluobo.lib_http.Const
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/8/4.
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun VideoPagerPage(navHostController: NavHostController, vm: VideoViewModel = hiltViewModel()) {
    val json = MMKV.defaultMMKV().decodeString(Const.KEY_VIDEO_PAGER)
    val list = Gson().fromJson(json, VideoEntity::class.java)
    val context = LocalContext.current

    val pagerState = rememberPagerState {
        list.size
    }

    //播放器列表
    val players = remember {
        mutableListOf<ExoPlayer>()
    }

    //优化版的状态
    val currentPage by remember {
        derivedStateOf { pagerState.currentPage }
    }

    var liked by remember {
        mutableStateOf(false)
    }

    var isCollect by remember {
        mutableStateOf(false)
    }

    var isShowComment by remember {
        mutableStateOf(false)
    }

    var currentIndex by remember {
        mutableStateOf(-1)
    }

    val commentList = remember {
        SnapshotStateList<CommentEntityItem>()
    }


    //初始化
    DisposableEffect(list.size) {
        //重复列表的次数
        repeat(list.size) {
            players.add(createPlayer(context).apply {
                //添加播放地址
                setMediaItem(MediaItem.fromUri(list[it].videopath))
                prepare()
            })
        }
        //当页面销毁时,释放所有的播放器
        onDispose {
            players.forEach { it.release() }
        }
    }

    //根据当前的页面来判断
    LaunchedEffect(currentPage) {
        //循环列表中的数据
        players.forEachIndexed { index, exoPlayer ->
            //如果当前页面的下标等于循环中的下标,可以播放,其他位置播放器暂停
            if (index == currentPage) exoPlayer.play() else exoPlayer.pause()
        }
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnFailed -> {
                        ToastUtils.showLong("点赞/取消点赞失败:${it.msg}")
                        Log.e("TagA", "点赞/取消点赞失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        if (it.type == StateType.LIKE_VIDEO) {
                            ToastUtils.showLong("点赞成功")
                            list[currentIndex].dianzan = 1
                        }

                        if (it.type == StateType.NO_LIKE_VIDEO) {
                            ToastUtils.showLong("取消点赞成功")
                            list[currentIndex].dianzan = 0
                        }

                        if (it.type == StateType.COMMENT) {
                            commentList.clear()
                            commentList.addAll(it.data as CommentEntity)
                            Log.e("TagA", "comments:${commentList.size}")
                        }

                        if (it.type == StateType.COLLECT) {
                            ToastUtils.showLong("收藏成功")
                        }
                    }
                }
            }
        }
    })

    VerticalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { index ->
        //根据type区分多布局
        when (list[index].type) {
            0 -> {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomEnd) {
                    //每一个页面
                    AndroidView(
                        factory = {
                            PlayerView(it).apply {
                                player = players[index]
                                useController = true
                            }
                        }, modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black)
                    )
                    AndroidView(factory = {
                        val likeView = LikeView(it)
                        likeView
                    }, modifier = Modifier.fillMaxSize())
                    //用户交互的UI
                    Column(modifier = Modifier.padding(10.dp)) {
                        IconButton(onClick = {
                            currentIndex = index
                            liked = !liked
                            if (list[index].dianzan == 0) {
                                vm.sendIntent(VideoIntent.LikeVideo(list[index].id))
                            } else {
                                vm.sendIntent(VideoIntent.NoLikeVideo(list[index].id))
                            }
                        }) {
                            Icon(
                                imageVector = if (liked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                                contentDescription = "",
                                tint = if (liked) Color.Red else Color.White,
                                modifier = Modifier.size(40.dp)
                            )
                        }

                        IconButton(onClick = {
                            isShowComment = !isShowComment
                        }) {
                            Icon(
                                painter = painterResource(id = R.drawable.baseline_chat_24),
                                contentDescription = "",
                                tint = Color.White,
                                modifier = Modifier.size(40.dp)
                            )
                        }

                        IconButton(onClick = {
                            isCollect = !isCollect
                            if (list[index].address.isNullOrEmpty()) {
                                list[index].address = "天津八维学校"
                            }
                            vm.sendIntent(VideoIntent.CollectVideo(list[index]))
                        }) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = "",
                                tint = if (isCollect) Color.Cyan else Color.White,
                                modifier = Modifier.size(40.dp)
                            )
                        }
                    }

                    if (isShowComment) {
                        vm.sendIntent(VideoIntent.GetComments(list[index].id))
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(300.dp)
                                .background(Color.White, RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp)),
                            contentAlignment = Alignment.TopEnd
                        ) {

                            LazyColumn(content = {
                                items(commentList) {
                                    CommentItem(commentEntityItem = it)
                                }
                            })

                            Icon(imageVector = Icons.Default.Close, contentDescription = "", modifier = Modifier
                                .clickable {
                                    isShowComment = false
                                }
                                .padding(end = 10.dp, top = 10.dp))
                        }
                    }
                }
            }

            1 -> {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomEnd) {
                    //每一个页面
                    AndroidView(
                        factory = {
                            PlayerView(it).apply {
                                player = players[index]
                                useController = true
                            }
                        }, modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black)
                    )

                    //用户交互的UI
                    Column(modifier = Modifier.padding(10.dp)) {
                        IconButton(onClick = {
                            currentIndex = index
                            liked = !liked
                            if (list[index].dianzan == 0) {
                                vm.sendIntent(VideoIntent.LikeVideo(list[index].id))
                            } else {
                                vm.sendIntent(VideoIntent.NoLikeVideo(list[index].id))
                            }
                        }) {
                            Icon(
                                imageVector = if (liked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                                contentDescription = "",
                                tint = if (liked) Color.Red else Color.White,
                                modifier = Modifier.size(40.dp)
                            )
                        }

                        IconButton(onClick = {
                            isShowComment = !isShowComment
                        }) {
                            Icon(
                                painter = painterResource(id = R.drawable.baseline_chat_24),
                                contentDescription = "",
                                tint = Color.White,
                                modifier = Modifier.size(40.dp)
                            )
                        }
                    }

                    if (isShowComment) {
                        vm.sendIntent(VideoIntent.GetComments(list[index].id))
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(300.dp)
                                .background(Color.White, RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp)),
                            contentAlignment = Alignment.TopEnd
                        ) {

                            LazyColumn(content = {
                                items(commentList) {
                                    CommentItem(commentEntityItem = it)
                                }
                            })

                            Icon(imageVector = Icons.Default.Close, contentDescription = "", modifier = Modifier
                                .clickable {
                                    isShowComment = false
                                }
                                .padding(end = 10.dp, top = 10.dp))
                        }
                    }
                }
            }

            2 -> {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomEnd) {
                    //每一个页面
                    AndroidView(
                        factory = {
                            PlayerView(it).apply {
                                player = players[index]
                                useController = true
                            }
                        }, modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black)
                    )

                    //用户交互的UI
                    Column(modifier = Modifier.padding(10.dp)) {
                        IconButton(onClick = {
                            currentIndex = index
                            liked = !liked
                            if (list[index].dianzan == 0) {
                                vm.sendIntent(VideoIntent.LikeVideo(list[index].id))
                            } else {
                                vm.sendIntent(VideoIntent.NoLikeVideo(list[index].id))
                            }
                        }) {
                            Icon(
                                imageVector = if (liked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                                contentDescription = "",
                                tint = if (liked) Color.Red else Color.White,
                                modifier = Modifier.size(40.dp)
                            )
                        }

                        IconButton(onClick = {
                            isCollect = !isCollect
                            if (list[index].address.isNullOrEmpty()) {
                                list[index].address = "天津八维学校"
                            }
                            vm.sendIntent(VideoIntent.CollectVideo(list[index]))
                        }) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = "",
                                tint = if (isCollect) Color.Cyan else Color.White,
                                modifier = Modifier.size(40.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}

//创建播放器
private fun createPlayer(context: Context): ExoPlayer {
    return ExoPlayer.Builder(context).build().apply {
        repeatMode = REPEAT_MODE_ONE
        playWhenReady = true
    }
}

@Composable
fun CommentItem(commentEntityItem: CommentEntityItem) {
    Column(
        modifier = Modifier
            .padding(5.dp)
            .fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(5.dp)
    ) {
        Row {
            AsyncImage(
                model = commentEntityItem.icon, contentDescription = "", modifier = Modifier
                    .size(40.dp)
                    .clip(
                        CircleShape
                    ), contentScale = ContentScale.Crop
            )
            Spacer(modifier = Modifier.width(10.dp))
            Text(text = "${commentEntityItem.username}")
        }
        Text(text = "${commentEntityItem.msg}")
        Text(text = "${commentEntityItem.createtime}", fontSize = 12.sp, color = Color.Gray)
    }
}